import Ele from './Ele'
import Okay from '../Okay'
import ForParser from "../parser/ForParser";
import ForResolver from "../parser/ForResolver";
export default class ForEle extends Ele {
    constructor (subject, ele, lazy=false) {
        super(subject, ele, lazy)
        let code = ele.getAttribute('expre')
        if(!/\s*\w+\s+of\s+\w+\s*/u.test(code)){
            throw ele.outerHTML + '语法错误';
        }
        let l = code.split("of")
        this.dest = l[0].trim()
        this.source = l[1].trim()
        this.html = this.ele.innerHTML
        this.ele.innerHTML = ''
        this.okays = new Array()
    }
    getView () {
        return this.ele.getAttribute('expre')
    }
    getResolver () {
        return new ForResolver(this.subject, this)
    }
    getParser () {
        return new ForParser(this.getView())
    }
    draw () {
        super.draw()
        let target = this.fn.call(this.subject)
        for(let key = 0,len = target.length; key < len; key++) {
            this.createChild(target[key])
        }
    }
    createChild(pd_data) {
        let ele = document.createElement('item')
        ele.innerHTML = this.html
        let pd = {}
        pd[this.dest] = pd_data
        new Okay({
            ele: ele,
            data: this.subject.data,
            builder: this.subject.builder,
            parent: this,
            action_classes: this.subject.action_classes,
            filters:this.subject.filters,
            aop: this.subject.aop || {},
            parent_field: {
                key: this.dest,
                source: this.source,
                data: pd
            }
        })
        this.ele.appendChild(ele)
    }

    update (path, data) {
        if (data.method == 'push') {
            this.createChild(data.arguments)
        } else if (data.method == 'pop') {
            let target = this.okays.pop()
            this.ele.removeChild(target.ele.ele);
        }else {
            console.log(path)
            while(this.okays.length){
                let okay = this.okays.pop()
                okay.data.proxy.okays.delete(okay)
            }
            this.ele.innerHTML = ''
            // 重新监听数据变化
            let target = this.fn.call(this.subject)
            this.subject.data.proxy.proxy(target, path)
            for(let key = 0,len = target.length; key < len; key++) {
                this.createChild(target[key])
            }
        }

    }

}